package com.edouardbataille.open.util
{
	import com.edouardbataille.open.meta.MetaClass;
	import com.edouardbataille.open.result.ResultSet;
	
	import mx.core.mx_internal;
	import mx.rpc.AsyncToken;
	import mx.rpc.Fault;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class SaveResponder implements IResponder
	{
		private var clazz : Class;
		
		private var type : MetaClass;
		
		public var token : AsyncToken;
		
		private var obj : Object;
		
		public function SaveResponder(data : *, clazz : Class, type : MetaClass)
		{
			this.clazz = clazz;
			this.type = type;
			this.obj = data;
			token = new AsyncToken ();
		}

		public function result(data:Object):void
		{
			var res: ResultSet = ResultSet(data.result);
			
			obj[type.id.field] = res.lastInsertId;

			var event : ResultEvent = ResultEvent.createEvent(obj, token);
			token.dispatchEvent(event);
			event.mx_internal::callTokenResponders ();
		}
		
		public function fault(info:Object):void
		{
			var fault : Fault = info.fault;
			var event : FaultEvent = FaultEvent.createEvent(fault, token);
			token.dispatchEvent(event);
			event.mx_internal::callTokenResponders ();
		}
		
	}
}